package com.cy.controller;


import com.cy.dto.UserDTO;
import com.cy.entity.SysUser;
import com.cy.mapper.SysUserMapper;
import com.cy.mapstruct.UserMapstruct;
import com.cy.util.R;
import com.cy.vo.UserVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author wxhn1
 */
@RestController
@CrossOrigin
public class UserController {

	@Resource
	SysUserMapper sysUserMapper;
	
	/**
	 * 用户login
	 * @param userDTO 用户信息
	 * @return R<UserVO>
	 */
	@RequestMapping("login")
	public R<UserVO> login(@RequestBody UserDTO userDTO) {
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken t = new UsernamePasswordToken(userDTO.getYhm(), userDTO.getPwd());
		try {
			
			subject.login(t);
			
			// 取出登录成功得用户
			SysUser sysUser = (SysUser) subject.getPrincipal();
			List<String> roles = sysUserMapper.getRoles(sysUser.getUsername());
			
			// 实体类转VO
			UserVO userVO = UserMapstruct.USER_MAPSTRUCT.toUserVO(sysUser);
			userVO.setRole(roles.get(0));
			userVO.setToken(subject.getSession().getId().toString()); // 获取当前的会话id 写入到前端
			
			return R.ok(userVO);
		} catch ( UnknownAccountException e ) {
			return R.fail("账号不存在");
		} catch ( LockedAccountException e ) {
			return R.fail("账号已被锁定");
		} catch ( IncorrectCredentialsException e ) {
			return R.fail("密码错误");
		} catch ( Exception e ) {
			return R.fail("登录失败 服务器异常");
		}
	}
	
	@RequestMapping("id")
	public String id() {
		Subject subject = SecurityUtils.getSubject();
		return "本次访问的会话id为:" + subject.getSession().getId().toString();
	}
	
	@RequestMapping("tologin")
	public String tologin() {
		return "login";
	}
	
	@RequestMapping("unlogin")
	public String un(RedirectAttributes ra) {
		ra.addFlashAttribute("msg" , "请先登录");
		return "redirect:/tologin";
	}
}
